package com.wechat;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.http.HttpStatus;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

public class Wechat {


    public static void main(String[] args) {
      //  String access_token= "62_EsFEdjbRW5_A7xfKTKvG2CJevShWUiiH3kALI01c03bwSPBh2qky-YiTFPoScf3FJ-NytsrnlnbwRsqmcjW80FLFYCBCz0DaHAq1Wki8QLA";
        String access_token=  "62_4mA0rCMrXJSFJkGu3_Y0xUBwuFL_H00rnblmnLV7zGyQ4GtSU5p27wF3xM-1gs5f-Z38e4tZUkEsf3vXkmbhrkklakG426SoIdk-nz-eQEo";

        String  openid= "oI652506EOVCZJwjdxbcVart-VZU";


        userinfo(access_token,openid);
    }
    public static String userinfo(String access_token, String openId) {
        try {
            // 获取用户信息
          //  String getUser= "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";


            String getUser= "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";

            // String getUser="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
            JSONObject user = JSONObject.parseObject(doGet(getUser,null,null));
            System.out.println(JSONObject.toJSONString(user));
            String wechatName= (String) user.get("nickname");
            System.out.println("用户名为:{}，openid为:{}"+wechatName+openId);
        }catch (Exception e){
            System.out.println("获取用户信息异常!"+ e);
        }
        return "<h1 align=\"center\">您已授权成功</h1>";
    }

    /**
     * 发起GET请求（使用java原生方法）
     * @param url 请求路径
     * @param params 请求参数
     * @param headers 请求头
     */
    public static String doGet(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
        // 1.构造完整请求url（带参数）
        String fullUrl = buildUrl(url, params);
        System.out.println("full url is: " + fullUrl);

        // 2.打开连接
        HttpURLConnection conn = (HttpURLConnection) new URL(fullUrl).openConnection();

        // 3.设置请求方法为get
        conn.setRequestMethod("GET");

        // 4.设置请求头
        if (headers != null) {
            Set<String> headerKeys = headers.keySet();
            if (CollectionUtils.isNotEmpty(headerKeys)) {
                for (String headerKey : headerKeys) {
                    conn.setRequestProperty(headerKey, headers.get(headerKey));
                }
            }
        }

        // 5.获取响应状态码（非2开头状态码，认定请求失败）
        int statusCode = conn.getResponseCode();
        if (statusCode < HttpStatus.SC_OK || statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) {
            System.out.println("status code is: " + statusCode);
            System.out.println("error message is: " + getContent(conn.getErrorStream()));
            throw new Exception("response status code wrong, status code is: " + statusCode);
        }

        // 6.获取请求结果
        return getContent(conn.getInputStream());
    }

    /**
     * 构造完整请求url（带参数）
     * @param url 请求url，形如：http://192.168.1.19
     * @param params 请求参数，key是参数名，value是参数值
     * @return 构造好的url，形如：http://192.168.1.19?name=mark&base=jinan
     */
    public static String buildUrl(String url, Map<String, String> params) throws UnsupportedEncodingException {

        StringBuilder urlBuilder = new StringBuilder(url);

        if (params != null) {
            Set<String> keySet = params.keySet();
            if (CollectionUtils.isNotEmpty(keySet)) {
                urlBuilder.append("?");

                for (String key : keySet) {
                    urlBuilder.append(key)
                            .append("=")
                            .append(URLEncoder.encode(params.get(key), StandardCharsets.UTF_8.name()))
                            .append("&");
                }

                urlBuilder.deleteCharAt(urlBuilder.length() - 1);
            }
        }

        return urlBuilder.toString();
    }

    /**
     * 读取InputStream
     */
    private static String getContent(InputStream inputStream) throws IOException {
        try (BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8.name()))) {

            String line;
            StringBuilder result = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }

            return result.toString();
        }
    }


}
